<template>
  <div>
    <form-dialog
      ref="formDrawerRef"
      title="维修"
      top="5vh"
      width="90%"
      @submit="handleMaintainSubmit"
    >
      <div class="flex justify-end items-center">
        <div class="mr-4 text-[16px] font-bold">
          合计: <span class="text-red-500">¥{{ handleTotalPrice() }}</span>
        </div>
        <el-button type="primary" @click="handleAddProject">添加项目</el-button>
      </div>
      <div class="dialog-body">
        <template v-if="curProjectAccessoryList.length">
          <el-card class="mt-2" v-for="(item, index) in curProjectAccessoryList" :key="item.id">
            <template #header>
              <div class="flex justify-between items-center">
                <div>
                  <span class="font-bold text-base">{{ item.name }}</span>
                  <span class="ml-4"
                    >项目工时费:<span class="text-red-500">￥{{ item.price }}</span>
                    <span class="ml-4"
                      >合计:<span class="text-red-500"
                        >￥{{ handleProjectTotalPrice(item) }}</span
                      ></span
                    ></span
                  >
                </div>
                <div>
                  <el-button type="primary" @click="handleAddAccessory(index)">添加配件</el-button>
                  <el-popconfirm
                    width="220"
                    title="您确定要删除改服务项目?"
                    @confirm="handleDeleteProject(item)"
                  >
                    <template #reference><el-button type="danger">删除项目</el-button></template>
                  </el-popconfirm>
                </div>
              </div>
            </template>
            <el-table
              v-if="item.accessoryList.length"
              :data="item.accessoryList"
              :header-row-style="{ height: '40px' }"
            >
              <el-table-column label="名称" prop="name"></el-table-column>
              <el-table-column label="数量" prop="accessoryNumber">
                <template #default="{ row }">
                  <el-input-number
                    v-model="row.accessoryNumber"
                    :min="1"
                    :max="100"
                    @change="handleChangeNumber($event, row)"
                  />
                </template>
              </el-table-column>
              <el-table-column label="单价" prop="price"></el-table-column>
              <el-table-column label="总价" prop="allPrice">
                <template #default="{ row }">
                  {{ row.price * row.accessoryNumber }}
                </template>
              </el-table-column>
              <el-table-column label="操作">
                <template #default="{ row }">
                  <el-popconfirm
                    width="220"
                    title="您确定要删除该配件?"
                    @confirm="handleDeleteAccessory(row.id, index)"
                  >
                    <template #reference><el-button type="danger">删除</el-button></template>
                  </el-popconfirm>
                </template>
              </el-table-column>
            </el-table>
          </el-card>
        </template>
        <el-empty v-else description="暂无项目" />
      </div>
      <!-- 添加项目 -->
      <project-dialog ref="projectDialogRef" @submit="handleSumbitProject" />
      <!-- 添加配件 -->
      <accessory-dialog ref="accessoryDialogRef" @submit="handleSumbitAccessory" />
    </form-dialog>
  </div>
</template>
<script setup lang="ts">
import { ref, watch } from "vue";
import { ElMessage } from "element-plus";
import { useInitForm } from "@/hooks/useCommon";
import FormDialog from "@/components/FormDialog.vue";
import ProjectDialog from "./projectDialog.vue";
import AccessoryDialog from "./accessoryDialog.vue";
import useRepairStore from "@/stores/modules/repair";
import { toast } from "@/utils/index";
import { addProjectAccessoryApi } from "@/api/examine";

const emit = defineEmits(["success"]);
const useRepair = useRepairStore();
// 当前选择维修单信息
const curInfo = ref<any>({});
// 维修
const { formDrawerRef, handleCreate } = useInitForm({});
const curProjectAccessoryList = ref<any[]>([]);
// 项目
const projectDialogRef = ref<InstanceType<typeof ProjectDialog>>();
// 添加项目-按钮
const handleAddProject = () => {
  projectDialogRef.value?.open();
};
// 选择项目-确定
const handleSumbitProject = (val: any) => {
  val.forEach((item: any) => {
    const isHave = curProjectAccessoryList.value.findIndex((item1) => item1.id === item.id);
    if (isHave === -1) {
      curProjectAccessoryList.value.push({
        id: item.id,
        name: item.projectName,
        price: item.manHourAmount,
        accessoryList: []
      });
    }
  });
  projectDialogRef.value?.handleRestProject();
};

// 删除项目
const handleDeleteProject = (item: any) => {
  const index = curProjectAccessoryList.value.findIndex((item1) => item1.id === item.id);
  curProjectAccessoryList.value.splice(index, 1);
};

// 项目合计费用
const handleProjectTotalPrice = (val: any) => {
  let totalPrice = Number(val.price);
  if (val.accessoryList.length) {
    val.accessoryList.forEach((item: any) => {
      totalPrice += Number(item.price) * Number(item.accessoryNumber);
    });
  }
  return totalPrice || 0;
};

// 项目合计
const handleTotalPrice = () => {
  let totalPrice = 0;
  curProjectAccessoryList.value.forEach((item) => {
    totalPrice += handleProjectTotalPrice(item);
  });
  return totalPrice;
};

// 添加配件-按钮
const accessoryDialogRef = ref<InstanceType<typeof AccessoryDialog>>();
// 当前选择的项目
const curProject = ref();
// 点击添加配件按钮
const handleAddAccessory = (index: number) => {
  curProject.value = index;
  accessoryDialogRef.value?.open();
};

// 选择配件-确定
const handleSumbitAccessory = (val: any) => {
  const newItem = curProjectAccessoryList.value[curProject.value].accessoryList;
  val.forEach((item: any) => {
    const isHave = newItem.findIndex((item1: any) => item1.id === item.id);
    if (isHave === -1) {
      newItem.push({
        id: item.id,
        name: item.productName,
        accessoryNumber: 1,
        price: item.saleAmount,
        allPrice: item.saleAmount * 1
      });
    }
  });
  accessoryDialogRef.value?.handleRestAccessory();
};

// 修改配件数量
const handleChangeNumber = (e: any, val: any) => {
  // if (e > 3) {
  //   ElMessage.warning("数量不能大于3");
  // }
  val.accessoryNumber = e;
};
// 删除配件
const handleDeleteAccessory = (aid: any, pindex: any) => {
  const curProjectItem = curProjectAccessoryList.value[pindex];
  const curIndex = curProjectItem.accessoryList.findIndex((item: any) => item.id === aid);
  if (curIndex !== -1) {
    curProjectItem.accessoryList.splice(curIndex, 1);
  }
};

// 提交维修项目
const handleMaintainSubmit = async () => {
  if (!curProjectAccessoryList.value.length) {
    return ElMessage({ message: "至少添加一项服务项目", grouping: true, type: "warning" });
  }
  const curItem = curProjectAccessoryList.value.map((item) => {
    const newItem = item.accessoryList.map((item1: any) => ({
      productId: item1.id,
      num: item1.accessoryNumber
    }));
    return {
      projectId: item.id,
      productList: newItem
    };
  });
  try {
    (formDrawerRef.value as any).showLoading();
    await addProjectAccessoryApi({
      repairOrderId: curInfo.value.id,
      projectList: curItem
    });
    toast("服务项目提交成功");
    emit("success");
    (formDrawerRef.value as any).close();
  } finally {
    (formDrawerRef.value as any).hideLoading();
  }
};

// 回显服务项目和配件
const handleShowProjectAccessoryInfo = (val: any) => {
  curProjectAccessoryList.value = val.map((item: any) => {
    let curItem = [];
    if (item.productList) {
      curItem = item.productList.map((item1: any) => ({
        id: item1.productId,
        name: item1.productName,
        accessoryNumber: item1.num,
        price: item1.saleAmount,
        allPrice: item1.totalAmount
      }));
    }
    return {
      id: item.projectId,
      name: item.projectName,
      price: item.manHourAmount,
      accessoryList: curItem
    };
  });
};

// 当前选中的维修单
watch(
  () => useRepair.curOrder,
  (newVal) => {
    curInfo.value = newVal;
  },
  {
    immediate: true
  }
);

// 回显维修单的服务项目和配件
watch(
  () => useRepair.curProjectAccessoryInfo,
  (newVal) => {
    handleShowProjectAccessoryInfo(newVal);
  },
  {
    immediate: true
  }
);

defineExpose({
  handleCreate
});
</script>
<style scoped lang="scss">
.dialog-body {
  height: calc(100vh - 240px);
  overflow-y: auto;
}
</style>
